package com.lq.ecoldchain.ui.withdraw.mycard

import android.app.Activity
import android.arch.lifecycle.MutableLiveData
import android.content.Intent
import android.view.LayoutInflater
import com.lq.ecoldchain.R
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.BankCardEntity
import com.lq.ecoldchain.internet.BaseObserver
import com.lq.ecoldchain.util.toast

/*
*2019/1/7 0007  16:44
*function by lq
*/
class MyCardViewModel:BaseViewModel(){
    val refreshing by lazy { MutableLiveData<Boolean>() }
    val list by lazy { ArrayList<BankCardEntity>() }
    val adapter by lazy { CardListAdapter(list) }
    init {
        val view = LayoutInflater.from(App.instance).inflate(R.layout.empty_layout,null)
        adapter.emptyView = view
        obtainData()
        adapter.setOnItemChildClickListener { _, view, position ->
            val activity = view.context as Activity
            val resultIntent = Intent()
            resultIntent.putExtra("data",list[position])
            activity.setResult(-1,resultIntent)
            activity.finish()
        }
    }
    fun refreshData(){
        refreshing.value = true
        obtainData()
    }

    private fun obtainData(){
        BaseNetCore.ApiServiceImpl.bankCardList().compose(RxTransformer.switchSchedulers()).subscribe(object:BaseObserver<List<BankCardEntity>>(){
            override fun onSuccess(t: List<BankCardEntity>?) {
                if(!t.isNullOrEmpty()){
                    list.clear()
                    list.addAll(t)
                    adapter.notifyDataSetChanged()
                }
                if(refreshing.value==true)
                    toast { "刷新成功" }
                refreshing.value = false
            }

            override fun onFail(code: String) {
                refreshing.value = false
            }
        })
    }
}